<?php

namespace App\Services\MakeCouponsUsePoints;

use App\Models\User;
use App\Models\Order;
use Carbon\Carbon;
use App\Models\PointsProduct;
use App\Models\Coupon;
use App\Models\PointsProductRecord;
use Illuminate\Support\Facades\Redis;
use App\Http\Controllers\Api\V1\Requests\FormRequest;
use Rainsens\Dinglog\Facades\Dinglog;

class MakeCouponsUsePointRequest extends FormRequest
{
	public function rules()
	{

		return [
			'coupon_id' => [
				'required',
				'integer',
				'min:1',
				$this->coupon(),
			],
			'point_product_id' =>  [
				'required',
				'integer',
				'min:1',
				 $this->pointProduct()
			]
			
		];
	}

	public function pointProduct()
	{
		return function ($key, $value, $fail) {
			$pointProduct = PointsProduct::find($this->point_product_id);
			if(!$pointProduct){

				fail("该兑换商品不存在！");
			}

			if($pointProduct->coupon->id != $this->coupon_id){
				fail("该兑换商品不存在！");
			}
			if($pointProduct->stock < 1){

				fail("已抢光!");
			}
			if(big_decimal($this->user()->balances)->isLessThan($pointProduct->points)){

				fail("用户积分不足!");
			}

			$count=PointsProductRecord::query()->where("points_product_id",$pointProduct->id)->where("user_id",$this->user()->id)->whereDate("created_at",Carbon::now())->count();
			if(big_decimal($pointProduct->quantity)->isLessThanOrEqualTo($count)){

				fail("用户领取已达上限!");
			}

			return true;

		};	

	}

	public function coupon()
	{
		return function ($key, $value, $fail) {

			$coupon = Coupon::find($this->coupon_id);
			if($coupon->total < 1){

				fail("优惠卷已抢光");
			}
			return true;
		};
	}

	

}
